﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLocalChurch.Business;
using MyLocalChurch.Constants;
using MyLocalChurch.Models.Enumerations;
using MyLocalChurch.Models.KidsChurch;
using RKConsulting.Helpers;
using RKConsulting.Web.Helpers;

namespace MyLocalChurch.KidsChurch
{
    public partial class EditKid : System.Web.UI.Page
    {
        private readonly MyContext _context = MyContextSingleton.Instance;

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            Session[ImageHandler.SessionName] = null;

            var guardianId = QueryHelper.GetIntQueryParam(QueryParameters.GuardianId);
            var guardian = GuardianManager.GetGuardianAndUpdateCache(_context, guardianId);
            lblGuardianName.Text = guardian.ToString();

            ddlGender.BindEnumValues<Gender>();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            LoadKid();
        }

        protected void LoadKid()
        {
            var kidId = QueryHelper.GetIntQueryParam(QueryParameters.KidId);
            var kid = KidManager.GetKid(_context, kidId);

            txtFirstName.Text = kid.FirstName;
            txtMiddleName.Text = kid.MiddleName;
            txtLastName.Text = kid.LastName;
            txtNickName.Text = kid.NickName;
            ddlGender.SelectedValue = ((Gender)kid.Gender).ToString();
            dpBirthDate.SelectedDate = kid.BirthDate;
            txtAllergies.Text = kid.Allergies;
            txtRelationshipWithGuardian.Text = kid.RelationshipWithGuardian;
            txtAdditionalInformation.Text = kid.AdditionalInformation;

            if (kid.Photo != null)
            {
                Session[ImageHandler.SessionName] = kid.Photo.ImageData;
                var imageHandlerUrl = ConfigurationManager.AppSettings[AppSettingKeys.ImageHandlerUrl];
                imagePreview.ImageUrl = imageHandlerUrl;
            }
        }

        protected void btnPhotoPreview_Click(object sender, EventArgs e)
        {
            Session[ImageHandler.SessionName] = fileUploadPhoto.FileBytes;
            var imageHandlerUrl = ConfigurationManager.AppSettings[AppSettingKeys.ImageHandlerUrl];
            imagePreview.ImageUrl = imageHandlerUrl;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
                return;

            var guardianId = QueryHelper.GetIntQueryParam(QueryParameters.GuardianId);
            var kidId = QueryHelper.GetIntQueryParam(QueryParameters.KidId);
            var kid = KidManager.GetKid(_context, kidId);

            kid.FirstName = txtFirstName.Text;
            kid.MiddleName = txtMiddleName.Text;
            kid.LastName = txtLastName.Text;
            kid.NickName = txtNickName.Text;
            kid.Gender = (int)EnumHelper.Parse<Gender>(ddlGender.SelectedValue);
            kid.BirthDate = dpBirthDate.SelectedDate.HasValue
                                ? dpBirthDate.SelectedDate.Value
                                : default(DateTime);
            kid.Allergies = txtAllergies.Text;
            kid.RelationshipWithGuardian = txtRelationshipWithGuardian.Text;
            kid.AdditionalInformation = txtAdditionalInformation.Text;

            if (kid.Photo == null)
                kid.Photo = PhotoManager.CreatePhotoFromFileUploadOrSession(fileUploadPhoto, HttpContext.Current);
            else
            {
                var imageData = PhotoManager.GetImageDataFromFileUploadOrSession(fileUploadPhoto, HttpContext.Current);

                if (imageData != null && imageData.Length != 0)
                    kid.Photo.ImageData = imageData;

                if (fileUploadPhoto.PostedFile != null)
                {
                    kid.Photo.Name = fileUploadPhoto.PostedFile.FileName;
                    kid.Photo.ContentType = fileUploadPhoto.PostedFile.ContentType;
                }

                kid.ModifiedBy = SystemConstants.User;
                kid.ModifiedDate = DateTime.Now;
            }

            kid.ModifiedBy = SystemConstants.User;
            kid.ModifiedDate = DateTime.Now;

            _context.Entry(kid).State = EntityState.Modified;
            _context.SaveChanges();

            Response.Redirect(string.Concat("KidsList.aspx?", QueryParameters.GuardianId, "=", guardianId));
        }

        protected void RefreshKidCategory()
        {
            if (!dpBirthDate.SelectedDate.HasValue)
            {
                lblKidCategory.Text = string.Empty;
                return;
            }

            lblKidCategory.Text = KidManager.GetKidCategory(dpBirthDate.SelectedDate.Value).ToString();
        }

        protected void txtBirthDate_TextChanged(object sender, EventArgs e)
        {
            RefreshKidCategory();
        }
    }
}